<?php 
namespace Home\Controller;

use Think\Page;

class BlogController extends BaseController{
    
    public function index(){
        
        // 获取栏目名称
        $cat_id = I('get.cat_id');
        
        $cat_name = M('cat')->where(array('cat_id'=>$cat_id))->getField('cat_name');
        
        // 分页
        $totalRows = M('blog')->where(array('cat_id'=>$cat_id))->count();
        $page = new Page($totalRows,5);
        $show = $page->show();
        
        // 获取栏目下的博客
        $blogs = M('blog')->where(array('cat_id'=>$cat_id))->limit($page->firstRow.','.$page->listRows)->select();
        
        // 获取标签云
        $keys = M('keys')->order('count desc')->limit(10)->select();
        
        if (!empty($keys)){
            $max_count = $keys[0]['count'];
            $min_count = $keys[count($keys)-1]['count'];
            $space = ($max_count - $min_count)/10;
            
            $font = 14;
            foreach ($keys as $k=>$v){
                $size = ceil(($v['count'] - $min_count)/$space)*2;
                $keys[$k]['font'] = $size + $font;
            }
        }
        
        shuffle($keys);
        
        // 传递数据
        $this->assign('cat_name',$cat_name);
        $this->assign('blogs',$blogs);
        $this->assign('show',$show);
        $this->assign('keys',$keys);
        
        $this->display('blog_list');
    }
    
    // 跳转博客详情前检查是否购买
    public function checkDetails(){
        // 判断是否登录
        if (!session('?user')){
            $this->ajaxReturn(array('state'=>-1));
        }
        
        // 已登录 判断当前文章是否购买
        // 获取文章id
        $blog_id = I('post.blog_id');
        $user_id = session('user.id');
        
        // 查询数据
        $info = M('user_buy')->where(array('blog_id'=>$blog_id,'user_id'=>$user_id))->find();
        
        if(empty($info)){ // 未购买
            
        }else { // 购买
            $this->ajaxReturn(array('state'=>1));
        }
    }
    
    // 购买博客
    public function buyBlog(){
        // 获取博客id
        $blog_id = I('post.blog_id');
        $user_id = session('user.id');
        
        $price = I('post.money');
        
        // 获取账户余额
        $user_money = M('user')->where(array('id'=>$user_id))->getField('money');
        $res = $user_money - $price;
        if ($res > 0){ // 可以购买
            $res = M('user')->where(array('id'=>$user_id))->setField('money',$res);
            if($res){
                
                // 记录购买
                setUserLog($user_id, 2, '购买文章', 1,-$price);
                
                $this->ajaxReturn(array('state'=>1));
            }else{
                $this->ajaxReturn(array('state'=>0,'msg'=>'购买失败，请稍后重试'));
            }
        }else { // 余额不足
            
            $this->ajaxReturn(array('state'=>0,'msg'=>'余额不足'));
        }
    }
    
    
    
    
    
    
}
?>